package models

import (
	"errors"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	_ "github.com/go-sql-driver/mysql"
	"strconv"
	"strings"
	"time"
)

type IpccConfSign struct {
	Id        int            `orm:"description(唯一标识);pk;auto"`
	ServiceId string         `orm:"description(坐席Id)"`
	Number    string         `orm:"description(接听号码)"`
	Que       *IpccConfQueue `orm:"description(绑定队列);rel(fk);column(skill)"`
	AppId     string         `orm:"description(归属企业)"`
	Display   string         `orm:"description(外显)"`
	Active    bool           `orm:"description(签入有效)"`
	SignTime  time.Time      `orm:"description(签入时间);auto_now_add; type(datetime)"`
	Expaire   time.Time      `orm:"description(失效时间);null"`
}

func RegisterSign() {
	orm.RegisterModel(new(IpccConfSign))
}

func StoreSignIn(appId, queId, number, serviceId, display string) error {

	ns := IpccConfSign{
		ServiceId: serviceId,
		Number:    number,
		AppId:     appId,
		Display:   display,
		SignTime:  time.Now(),
		Active:    true,
	}

	o := orm.NewOrm()

	queue := &IpccConfQueue{}
	if queId == "default" {
		//获取默认技能组Id
		err := o.QueryTable("IpccConfQueue").
			Filter("Name", "default").
			Filter("AppId", appId).
			One(queue)
		if err != nil {
			logs.Error("默认技能组不存在,签入失败")
			return err
		}

	} else {
		queue.Id, _ = strconv.Atoi(queId)
		queue.AppId = appId
	}

	ns.Que = queue

	exist := &IpccConfSign{}
	err := o.QueryTable("IpccConfSign").
		Filter("ServiceId", ns.ServiceId).
		Filter("Que", ns.Que).
		Filter("AppId", ns.AppId).
		One(exist)
	if err != nil {
		//不存在的情况，插入
		if strings.ContainsAny(err.Error(), "found") {
			_, err = o.Insert(&ns)
		} else {
			return fmt.Errorf("数据库操作失败")
		}
	}

	return nil
}

func StoreSignOff(companyId, queId, serviceId string) error {

	ns := IpccConfSign{
		ServiceId: serviceId,
		AppId:     companyId,
		Active:    false,
		Expaire:   time.Now(),
	}

	o := orm.NewOrm()
	if len(queId) == 0 {
		_, err := o.Delete(&ns, "AppId", "ServiceId")
		logs.Debug("company %v service %v sign off all que", companyId, serviceId)
		return err
	}

	queue := &IpccConfQueue{}
	err := o.QueryTable("IpccConfQueue").
		Filter("Id", queId).
		Filter("AppId", companyId).
		One(queue)
	if err != nil {
		return err
	}

	ns.Que = queue
	_, err = o.Delete(&ns, "AppId", "Que", "ServiceId")
	if err == nil {
		logs.Debug("company %v service %v sign off from que:%v", companyId, serviceId, queId)
	}

	return err
}

func LoadSignIn(offset int) ([]*IpccConfSign, error) {

	var res []*IpccConfSign
	o := orm.NewOrm()

	n, err := o.QueryTable(new(IpccConfSign)).Filter("Active", true).
		RelatedSel("Que").
		Offset(offset * 100).
		Limit(100).
		All(&res)
	if n == 0 {
		return nil, errors.New("EOF")
	}

	return res, err

}
